<?php


namespace app\admin\controller\wechat;

use app\admin\controller\Base;
use think\facade\Request;
use think\facade\View;
use think\facade\Db;
use app\common\model\Wechat as WechatModel;
use helper\Wechat as WechatClass;
use helper\Menu as Menu;
use EasyWeChat\Factory;
use think\facade\Log;

class Wxmenu extends Base
{
    protected $app;
	protected $Wechat;
    protected $eventType = [
        'click' => '匹配规则',
        'view' => '跳转网页',
        'miniprogram' => '跳转小程序',
    ];
    public function initialize()
    {
        parent::initialize(); 
        $map[] = ['status','=',1];
        $wx = WechatModel::where($map)->find();
        $this->Wechat = new WechatClass($wx['domain']);
        $this->app = Factory::officialAccount($this->Wechat->get_config());
        $this->wechatConfig = WechatModel::loadList([],100);
        View::assign('wechat',$this->wechatConfig['list']);
        View::assign('eventType',$this->eventType);
    }
    
    public function index()
    {
        if ($this->request->isPost()) {
        	$wechat_id = $this->request->post('wechat_id');
			$arr = Db::name('wx_menu')->where('wx_id',$wechat_id)->order('sort asc')->select()->toArray();
            foreach ($arr as $key => $value) {
                $arr[$key]['menu_event'] = $this->eventType[$value['menu_event']];
            }
            if($arr){
            	return $result = ['code'=>0,'msg'=>lang('get info success'),'data'=>$arr];
            }else{
            	return $result = ['code'=>0,'msg'=>'暂无数据','data'=>$arr];
            }
            
        }
        return view();
    }
    
    public function selectKey()
    {
        if (request()->isPost()) {
            if (!$this->request->post('wx_id')) {
                return $result = ['code' => 0, 'msg' => '无数据', 'data' => []];
            }
            $where[] = ['wx_id','=',$this->request->post('wx_id')]; 
            $list = Db::name('wx_keys')->field('id,keys')->where($where)->order('id desc')->select()->toArray();
            
            return $result = ['code' => 1, 'msg' => lang('get info success'), 'data' => $list];
        }
        $wx_id = $this->request->get('wx_id');
        View::assign('wx_id',$wx_id);
        return view();
    }
    public function add()
    {
        if ($this->request->isPost()) {
        	$data = $this->request->post();
        	if (empty($data['title'])) {
        		$this->error('微信名称不能为空');
        	}
        	$data['createtime'] = time();
        	$data['updatetime'] = time();
        	if(Db::name('wx_menu')->insert($data)){
        		$this->success('添加成功',url('index'));
        	}else{
        		$this->error('添加失败');
        	}
        }else{
        	$parentid = input('param.parentid');
        	
            $view = [
                'info' => '',
                'parentid' => $parentid,
            ];
            View::assign($view);
            return view();
        }
    }
    public function get_menu(){
    	$wx_id = $this->request->post('wx_id');
    	$menu = new Menu();
    	$menuList = Db::name('wx_menu')->where('wx_id',$wx_id)->order('sort asc,id desc')->select();
    	$menuList = $menu->tree($menuList);
    	echo json_encode(['code'=>1,'msg'=>'获取成功','data'=>$menuList],320);die;
    	
    }
    public function menuOrder(){
        if (Request::isPost()) {
            $id = Request::param('id');
            $sort = Request::param('sort');
            $info = Db::name('wx_menu')->find($id);
            Db::name('wx_menu')->where('id',$id)->update(['sort'=>$sort]);
            $this->success(lang('edit success'));
        }
    }
    public function setMenu()
	 {
	 	if ($this->request->isPost()) {
	 		$wx_id = $this->request->post('wx_id');
	 		$map[] = ['wx_id','=',$wx_id];
	 		$data = Db::name('wx_menu')->field('id,pid,title,menu_event,menu_event_url')->where($map)->order('sort asc,id desc')->select()->toArray();
	 		// // print_r($data);die;
	 		$buttons = $this->menutree($data);
	 		$buttons = array_merge($buttons);
	 		// Log::mylog('wxmessage',$buttons,'message');
	 		// die;
			$setRes = $this->app->menu->create($buttons);
			
			if ($setRes['errcode'] == 0) {
				echo json_encode(['code'=>1,'msg'=>'保存成功']);die;
			} else {
				echo json_encode(['code'=>0,'msg'=>'保存失败']);die;
			}
			
	    	
	 	}
	 	
	 }
	 
	 public function menutree($data, $pid = 0){
	 	$listarr = [];  
		foreach ($data as $k => $v){
            if($v['pid']==$pid){
            	$temp["name"] = $v['title'];
            	
                $listarr[$k]=$temp;
                $sub = $this->menutree($data,$v['id']);
                if ($sub) {
                	$listarr[$k]['sub_button']= array_merge($sub);
                }else{
                	$listarr[$k]['type'] = $v['menu_event'];
	            	if($v['menu_event'] == 'click'){
	            		$listarr[$k]['key'] = 'key_'.$v['id'];
	            	}elseif($v['menu_event'] == 'view'){
	            		$listarr[$k]['url'] = $v['menu_event_url'];
	            	}
                }
                
            }
        }
		return $listarr;  
	 }
    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        if ($this->request->isPost()) {
        	$data = $this->request->post();
        	if (empty($data['title'])) {
        		$this->error('微信名称不能为空');
        	}
        	$data['updatetime'] = time();
        	if(Db::name('wx_menu')->where('id',$data['id'])->update($data)){
        		$this->success('修改成功',url('index'));
        	}else{
        		$this->error('修改失败');
        	}
        }else{
        	$info = Db::name('wx_menu')->where('id',$id)->find();
        	$menu = new Menu();
        	$menuList = Db::name('wx_menu')->order('sort asc,id desc')->select();
        	$menuList = $menu->tree($menuList);
            $view = [
                'info' => $info,
                'menulist' => $menuList,
            ];
            View::assign($view);
            return view();
        }
    }
    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
